<template>
  <div>
    <h1>App</h1>
    <div>
      <input type="text" v-model="title"> <button @click="add">+</button>
    </div>
    <div>
      <button :class="{ active: active === 0 }" @click="searchByStatus(0)">全部</button>
      <button :class="{ active: active === 1 }" @click="searchByStatus(1)">未完成</button>
      <button :class="{ active: active === 2 }" @click="searchByStatus(2)">进行中</button>
      <button :class="{ active: active === 3 }" @click="searchByStatus(3)">已完成</button>
    </div>
    <div>
      <table border="1">
        <thead>
          <tr>
            <th>标题</th>
            <th>状态</th>
            <th>操作</th>
            <th>修改状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for=" li in lists" :key="li.id" :class="rowCls[li.status]">
            <td>{{ li.title }}</td>
            <td>{{ status[li.status] }}</td>
            <td>
              <button @click="del(li.id)">X</button>
            </td>
            <td>
              <button v-show="li.status !== 1" @click="setStatus(li.id, 1)">未完成</button>
              <button v-show="li.status !== 2" @click="setStatus(li.id, 2)">进行中</button>
              <button v-show="li.status !== 3" @click="setStatus(li.id, 3)">已完成</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';

import axios from 'axios'
const request = axios.create({
  baseURL: 'http://127.0.0.1:3009',
})

const status = {
  1: '未完成',
  2: '进行中',
  3: '已完成'
}

const rowCls = {
  1: 's1',
  2: 's2',
  3: 's3',
}
const active = ref(0);
const title = ref('');

const lists = ref([]);

// 发起请求，获取list列表数据
const getLists = async function (where = {}) {
  const { data } = await request.get('/lists', {
    params: {
      ...where
    }
  });
  lists.value = data;
}

// 添加
const add = async function () {
  if (title.value === '') { return; }
  await request.post('/lists', {
    title: title.value,
    status: 1
  });
  title.value = '';
  getLists();//刷新页面
}

//删除
const del = async function (id) {
  if (confirm('确定删除吗') === false) { return; }
  await request.delete(`/lists/${id}`);
  getLists();//刷新页面
}
// 更新

const setStatus = async function (id, status) {
  await request.patch(`/lists/${id}`, {
    status,
  });

  getLists();//刷新页面
}

// 搜索
const searchByStatus = function (status) {
  active.value = status;
  if (status === 0) {
    getLists();
  } else {
    getLists({ status });//刷新页面
  }
};
onMounted(() => {
  getLists();
})
</script>

<style>
.active {
  background: yellowgreen;
  color: white;
}

.s1 {
  background-color: rgb(250, 215, 238);
}

.s2 {
  background-color: antiquewhite;
}

.s3 {
  background-color: rgb(232, 250, 215);
}

div {
  border: solid;
  padding: 10px;
}
</style>